package com.ywy.svgtest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MapView extends View {
    private Context context;
    private Paint mPaint;
    private float scale = 1.0f;
    private int[] colorArray = new int[]{0xFF239BD7, 0xFF30A9E5, 0xFF80CBF1, 0xFF60B0F0};
    private List<ProviceItem> itemList;
    private ProviceItem select;
    private RectF totalRect;

    //                中国地图的  矩形
    float left = -1;
    float right = -1;
    float top = -1;
    float bottom = -1;
    private ClickListener mListener;


    public MapView(Context context) {
        this(context, null);
    }

    public MapView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init(context);
    }

    //初始化view
    private void init(Context context) {
        this.context = context;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        locatThread.run();


    }

    public MapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    Thread locatThread = new Thread() {
        @Override
        public void run() {
            InputStream inputStream = context.getResources().openRawResource(R.raw.china);
            List<ProviceItem> list = new ArrayList();

            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = null;
                builder = factory.newDocumentBuilder();
                Document doc = builder.parse(inputStream);
                Element rootElement = doc.getDocumentElement();
                NodeList items = rootElement.getElementsByTagName("path");


                for (int i = 0; i < items.getLength(); i++) {
                    Element element = (Element) items.item(i);
                    String pathData = element.getAttribute("d");
                    String name = element.getAttribute("title");
                    Path path = PathParser.createPathFromPathData(pathData);
                    ProviceItem proviceItem = new ProviceItem(path);
                    proviceItem.setName(name);
                    list.add(proviceItem);

                    RectF rect = new RectF();
                    path.computeBounds(rect , true);

                    left = (left == -1) ? rect.left : Math.min(left , rect.left);
                    top = (top == -1) ? rect.top : Math.min(top , rect.top);
                    right = (right == -1) ? rect.right : Math.max(right , rect.right);
                    bottom = (bottom == -1) ? rect.bottom : Math.max(bottom , rect.bottom);


                }
                totalRect = new RectF(left , top , right , bottom);
                itemList = list;
                handler.sendEmptyMessage(1);


            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (itemList == null) {
                return;
            }
            int totalNumber = itemList.size();
            for (int i = 0; i < totalNumber; i++) {
                int color = Color.WHITE;
                int flag = i % 4;
                switch (flag) {
                    case 1:
                        color = colorArray[0];
                        break;
                    case 2:
                        color = colorArray[1];
                        break;
                    case 3:
                        color = colorArray[2];
                        break;
                    default:
                        color = colorArray[3];
                        break;
                }
                itemList.get(i).setDrawColor(color);
            }
            postInvalidate();
        }
    };


    @Override
    protected void onDraw(Canvas canvas) {
        if(itemList!=null){
//            canvas.save();
            canvas.scale(scale,scale);
            for (ProviceItem item:itemList) {
                if(item != select){
                    item.drawItem(canvas,mPaint , false);
                }

            }

            if(select !=null){
                select.drawItem(canvas , mPaint , true);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);


        if(totalRect != null){
            double mapWidth = totalRect.width();
            double mapHeight = totalRect.height();

            float wScale = (float) (width/mapWidth);
            float hScale = (float) (height/mapHeight);

            scale = Math.min(wScale,hScale);
            Log.e("map_view", "onMeasure: scale is " + scale );

        }


        setMeasuredDimension(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(height , MeasureSpec.EXACTLY));

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        handlerTouch(event.getX() , event.getY());

        return super.onTouchEvent(event);
    }

    private void handlerTouch(float x, float y) {

        if (itemList == null) {
            return;
        }

        ProviceItem selectItem = null;

        for (ProviceItem item :itemList) {
            if(item.isTouch(x/scale , y/scale)){
                selectItem = item;

                if(mListener != null){
                    mListener.onClick(item.getName());
                }

            }

        }

        if(selectItem!=null){
            select =  selectItem;
            postInvalidate();
        }
    }

    void setClickListener(ClickListener listener){

        mListener = listener;
    }



    interface ClickListener {
        void onClick(String name);
    }


}


